package com.zlyx.easy.log.loggers;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;

import com.zlyx.easy.core.annotations.ApplicationBean;
import com.zlyx.easy.core.event.LogEvent;
import com.zlyx.easy.core.map.Maps;
import com.zlyx.easy.core.utils.ExceptionUtils;
import com.zlyx.easy.log.handler.ILogHandler;
import com.zlyx.easy.log.model.LogModel;

/**
 * @Auth 赵光
 * @Desc 日志采集器
 * @2018年12月13日 下午2:52:09
 */
@ApplicationBean(value = "loggerFactory", todo = "")
public class LoggerFactory implements ApplicationListener<LogEvent> {

	private static Map<Class<?>, Logger> loggers = Maps.newMap();

	@Autowired(required = false)
	private List<ILogHandler> handlers;

	/**
	 * 获取参数类日志对象
	 * 
	 * @return
	 */
	public static Logger getLogger() {
		return getLogger(ExceptionUtils.getCurrentClass());
	}

	/**
	 * 获取参数类日志对象
	 * 
	 * @param cls
	 * @return
	 */
	public static Logger getLogger(Class<?> cls) {
		return getLogger(cls, false);
	}

	/**
	 * 获取参数类日志对象
	 * 
	 * @param c
	 * @return
	 */
	public static Logger getLogger(Class<?> cls, boolean isCache) {
		Logger logger = loggers.get(cls);
		if (logger == null) {
			logger = Logger.getLogger(cls);
			if (isCache) {
				loggers.put(cls, logger);
			}
		}
		return logger;
	}

	@Override
	public void onApplicationEvent(LogEvent event) {
		List<LogModel> logs = Arrays.asList(new LogModel(event));
		if (handlers != null && handlers.size() > 0) {
			for (ILogHandler handler : handlers) {
				handler.handle(logs);
			}
		}
	}
}
